//
//  YCLEmoticonModel.swift
//  02.表情键盘
//
//  Created by yaochunlin on 16/4/25.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

//表情模型
class YCLEmoticonModel: NSObject , NSCoding{

    //属性
    //表情名称
    var chs: String?
    //表情图片名称
    var png: String? {
    
        didSet{
        
            pngPath = EmoticonsBundlePath + "/" + id + "/" + png!
        }
    }
    /// emoji 16进制字符串
    var code: String? {
        didSet {
            // 将 code 转成 emoji字符串
            
            let scanner = NSScanner(string: code!)
            
            var result: UInt32 = 0
            scanner.scanHexInt(&result)
            
            emoji = "\(Character(UnicodeScalar(result)))"
        }
    }
    
    // emoji字符串
    var emoji: String?
    
    //png完整路径(bundle/表情包文件夹名称/png)
    var pngPath: String?
    
    //表情包文件夹
    var id: String
    //字典转模型
    init(dict: [String : AnyObject], id: String) {
        
        self.id = id
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
    
        return "表情模型: chs:\(chs), png:\(png), code:\(code)"
    }
    
    
    // MARK: - 归档和解档
    required init?(coder aDecoder: NSCoder) {
        id = aDecoder.decodeObjectForKey("id") as? String ?? ""
        chs = aDecoder.decodeObjectForKey("chs") as? String
        png = aDecoder.decodeObjectForKey("png") as? String
//        pngPath = aDecoder.decodeObjectForKey("pngPath") as? String
        
        //每次运行沙盒路径是变化的
        if let p = png {
            
            pngPath = EmoticonsBundlePath + "/" + id + "/" + p
        }
        
        code = aDecoder.decodeObjectForKey("code") as? String
        emoji = aDecoder.decodeObjectForKey("emoji") as? String
    }
    //
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(id, forKey: "id")
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
        aCoder.encodeObject(pngPath, forKey: "pngPath")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(emoji, forKey: "emoji")
    }

}
